// pages/mystore/photos/index.js
import { getQiniuToken, cdnUrl, apiUrls, makeRequest } from '../../../utils/api';
import { uploadQiniu } from '../../../utils/upload';
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    photos: [],
    photos_local: [],
    qiniu_token: '',
    isAgree: true
  },
  onLoad: function (options) {
    let that = this;
    that.setData({
      id: options.id
    });
    that.wxValidate = App.wxValidate(
      {
        photos: {
          required: true,
        }
      }
      , {
        photos: {
          required: '店铺photos必须上传',
        }
      }
    );
    makeRequest({
      url: apiUrls.getShopDetail(options.id),
      method: 'GET',
      data: {
        include: 'category,manager,area'
      },
      success: function (res) {
        let photos_local = [];
        let photos = [];

        if (res.data.data.photos === '') {
          photos_local = cdnUrl + '1.png-c128';
        } else {
          res.data.data.photos.map((item) => {
            photos.push(cdnUrl + item)
          })
          photos_local = photos_local.concat(photos);
        }
        that.setData({
          photos_local: photos_local,
          photos: res.data.data.photos
        })
      }
    });
    makeRequest({
      url: apiUrls.getQiniuToken,
      method: 'GET',
      success: function (res) {
        that.setData({ qiniu_token: res.data.uptoken });
      }
    });
  },
  bindSubmit(e) {
    let that = this;
    console.log(e.detail.value)
    //提交错误描述
    if (!this.wxValidate.checkForm(e)) {
      const error = this.wxValidate.errorList[0]
      // `${error.param} : ${error.msg} `
      wx.showToast({
        title: `${error.msg} `,
        image: '/images/error.png',
        duration: 500
      })
      return false
    }
    else {
      makeRequest({
        url: apiUrls.putPhotosEdit(that.data.id),
        method: 'PUT',
        data: {
          photos: that.data.photos
        },
        success: function (res) {
          if (res.statusCode === 422) {
            wx.showToast({
              title: `${res.data.data[Object.keys(res.data.data)[0]][0]} `,
              image: '/images/error.png',
              duration: 500
            })
          } else if (res.statusCode === 200) {
            wx.showToast({
              title: '保存成功',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  });
                }, 1000);
              }
            });
          }
        }
      });
    }
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.form.photos // 需要预览的图片http链接列表
    })
  },
  chooseImage: function (e) {
    let that = this;
    wx.chooseImage({
      success: function (res) {
        const file = res.tempFilePaths[0];
        uploadQiniu(file, that.data.qiniu_token, function (qnres) {
          const key = JSON.parse(qnres.data).key;
          let index = that.data.photos.indexOf(key);
          if (index == -1) {
            that.setData({
              photos_local: Array.from(new Set(that.data.photos_local.concat(file))),
              photos: Array.from(new Set(that.data.photos.concat(key)))
            });
          }
        });
      }
    })
  },
  deleteImage: function (e) {
    let that = this;
    let index = that.data.photos_local.indexOf(e.currentTarget.id);
    wx.showActionSheet({
      itemList: ['预览', '替换', '删除'],
      success: function (res) {
        if (res.tapIndex == 0) {
          wx.previewImage({
            current: e.currentTarget.id, // 当前显示图片的http链接
            urls: that.data.photos_local // 需要预览的图片http链接列表
          })
        } else if (res.tapIndex == 1) {
          wx.chooseImage({
            success: function (resfile) {
              const file = resfile.tempFilePaths[0];
              uploadQiniu(file, that.data.qiniu_token, function (resfile) {
                const key = JSON.parse(resfile.data).key;

                let photos_local = [].concat(that.data.photos_local);
                let photos = [].concat(that.data.photos);

                photos.splice(index, 1, key);
                photos_local.splice(index, 1, file);

                  that.setData({
                    photos_local: photos_local,
                    photos: photos
                  });

              });
            }
          });
        } else if (res.tapIndex == 2) {
          let photos_local = that.data.photos_local.splice(index, 1);
          let photos = that.data.photos.splice(index, 1);
          that.setData({
            photos_local: that.data.photos_local,
            photos: that.data.photos
          });
        }
      },
      fail: function (err) {
        console.log('取消')
      }
    });

  }
})